<?php

namespace App\Models\Goods;
use App\Models\BaseModel;
use App\Params\Backend\BrandListParams;
use App\Params\Backend\BrandUpdateParam;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

/**
 * 商品品牌模型类
 *
 * @package App\Http\Models
 * @author WangBin
 * @date 2021-06-11
 */
class Brand extends BaseModel
{
    protected $table = 'b2c_goods_brand';
    protected $primaryKey = 'brand_id';

    /**
     * 根据ID查询品牌
     *
     * @param int $brandId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $brandId)
    {
        return Brand::query()->where('brand_id', $brandId)->first();
    }

    /**
     * 保存品牌信息
     *
     * @param BrandUpdateParam $data
     * @return bool
     */
    public static function saveData(BrandUpdateParam $data)
    {
        $brand = $data->getBrandId() ? Brand::find($data->getBrandId()) : new Brand();
        unset($data->brand_id);
        foreach ($data as $field => $value)
        {
            $brand->{$field} = $value;
        }
        return $brand->save() ? $brand->brand_id : 0;
    }

    /**
     * 获取品牌列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(BrandListParams $filter)
    {
        $brands = Brand::query();
        if($filter->getBrandName()) {
            $brands->where('name', 'like', '%' . $filter->getBrandName() . '%');
        }
        if(Arr::exists([0, 1], $filter->getIsActive())) {
            $brands->where('is_active', $filter->getIsActive());
        }
        $brands->orderByDesc('created_at');
        return $brands;
    }

    /**
     * 检测名称唯一
     *
     * @param string $name
     * @param int $id
     * @return bool
     */
    public static function checkName(string $name, int $id = 0)
    {
        $query = Brand::query()->where('name', $name);
        if($id) {
            $query->where('brand_id', '!=', $id);
        }
        return $query->exists();
    }
}
